package com.estate.web.controller.system;

import com.estate.common.constant.Constants;
import com.estate.common.core.domain.AjaxResult;
import com.estate.common.core.domain.model.LoginBody;
import com.estate.common.core.domain.model.LoginUser;
import com.estate.common.core.domain.resp.SysMenuResp;
import com.estate.common.core.domain.resp.SysUserResp;
import com.estate.common.utils.SecurityUtils;
import com.estate.common.utils.bean.BeanUtils;
import com.estate.framework.web.service.SysLoginService;
import com.estate.system.service.ISysMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 登录验证
 * 
 * @author ruoyi
 */
@RestController
public class SysLoginController
{
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    /**
     * 登录方法
     * 
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody)
    {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo()
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUserResp userInfo = new SysUserResp();
        BeanUtils.copyBeanProp(userInfo, loginUser.getUser());
        return AjaxResult.success(userInfo);
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters()
    {
        Long userId = SecurityUtils.getUserId();
        List<SysMenuResp> menus = menuService.selectMenuTreeByUserId(userId)
                .stream()
                .map(item -> {
                    SysMenuResp menuResp = new SysMenuResp();
                    BeanUtils.copyBeanProp(menuResp, item);
                    return menuResp;
                })
                .collect(Collectors.toList());
        return AjaxResult.success(menus);
    }
}
